package com.yupi.springbootinit.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yupi.springbootinit.service.workflow.WorkflowTaskCreationService;
import com.yupi.springbootinit.utils.JsonUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 质检事件监听器（生产环境推荐配置）
 */
@Slf4j
@Component
public class QualityInspectionEventListener {

    @Resource
    private WorkflowTaskCreationService taskCreationService;

    /**
     * 监听工序需要质检事件
     */
    // @RabbitListener(bindings = @QueueBinding(  // RabbitMQ 已暂停使用
    //         value = @Queue(value = "quality.inspection.queue", durable = "true"),
    //         exchange = @Exchange(value = "workflow.topic", type = "topic", durable = "true"),
    //         key = "production.step.need_inspection"
    // ))
    public void handleStepNeedInspection(String message) {
        log.info("收到工序需检事件: {}", message);

        try {
            Map<String, Object> payload = parseMessage(message);

            Long batchStepId = getLongValue(payload, "batchStepId");
            if (batchStepId == null) {
                log.error("工序需检事件参数错误: batchStepId为空");
                return;
            }

            taskCreationService.createQualityInspectionTask(
                    batchStepId,
                    getLongValue(payload, "batchId"),
                    (String) payload.get("orderNumber"),
                    (String) payload.get("operationName"),
                    getIntValue(payload, "stepNo"),
                    getLongValue(payload, "completedBy"),
                    (String) payload.get("completedByName")
            );

            log.info("质检任务创建成功: stepId={}", batchStepId);

        } catch (Exception e) {
            log.error("处理工序需检事件失败", e);
        }
    }

    /**
     * 监听质检失败事件
     */
    // @RabbitListener(bindings = @QueueBinding(  // RabbitMQ 已暂停使用
    //         value = @Queue(value = "quality.rework.queue", durable = "true"),
    //         exchange = @Exchange(value = "workflow.topic", type = "topic", durable = "true"),
    //         key = "quality.inspection.failed"
    // ))
    public void handleQualityInspectionFailed(String message) {
        log.info("收到质检不合格事件: {}", message);

        try {
            Map<String, Object> payload = parseMessage(message);

            Long batchStepId = getLongValue(payload, "batchStepId");
            if (batchStepId == null) {
                log.error("质检失败事件参数错误: batchStepId为空");
                return;
            }

            taskCreationService.createReworkTask(
                    batchStepId,
                    getLongValue(payload, "batchId"),
                    (String) payload.get("orderNumber"),
                    (String) payload.get("operationName"),
                    (String) payload.get("remark"),
                    getLongValue(payload, "operatorId"),
                    (String) payload.get("operatorName")
            );

            log.info("返工任务创建成功: stepId={}", batchStepId);

        } catch (Exception e) {
            log.error("处理质检失败事件失败", e);
        }
    }

    // ==================== 辅助方法 ====================

    private Map<String, Object> parseMessage(String message) throws Exception {
        ObjectMapper mapper = JsonUtils.getMapper();
        return mapper.readValue(message, Map.class);
    }

    private Long getLongValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return null;
        if (value instanceof Long) return (Long) value;
        if (value instanceof Number) return ((Number) value).longValue();
        try {
            return Long.parseLong(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }

    private Integer getIntValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) return null;
        if (value instanceof Integer) return (Integer) value;
        if (value instanceof Number) return ((Number) value).intValue();
        try {
            return Integer.parseInt(value.toString());
        } catch (NumberFormatException e) {
            return null;
        }
    }
}